package org.example.backend.service;

import org.springframework.stereotype.Service;
import jakarta.annotation.PostConstruct;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.*;
import java.util.stream.Collectors;
import org.example.backend.entity.PolicyInfo;
import org.example.backend.mapper.PolicyInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import com.huaban.analysis.jieba.JiebaSegmenter;
import com.huaban.analysis.jieba.SegToken;

@Service
public class AIAnalysisService {
    private String deepseekKey;
    private static final String DEEPSEEK_API = "https://api.deepseek.com/v1/chat/completions";

    @Autowired
    private PolicyInfoMapper policyInfoMapper;

    private final JiebaSegmenter jiebaSegmenter = new JiebaSegmenter();

    @PostConstruct
    public void init() {
        try {
            List<String> lines = Files.readAllLines(Paths.get("deepseek_key.txt"));
            if (!lines.isEmpty()) {
                deepseekKey = lines.get(0).trim();
            }
        } catch (IOException e) {
            deepseekKey = null;
        }
    }

    // 智能政策解读
    public Map<String, Object> interpretPolicy(Map<String, Object> policy) {
        String title = (String) policy.getOrDefault("title", "未知政策");
        String content = (String) policy.getOrDefault("content", "");
        String prompt = "你是资深政策分析师，请用专业视角对以下政策进行简明概括和要点总结。请直接输出要点内容，不要包含#、*、-、AI生成、总结、结论、分隔线等格式符号，只输出纯净的分析文本，可用一、二、三、等组织内容。" + title + "。政策内容：" + content;
        String aiSummary = callDeepSeek(prompt);
        Map<String, Object> result = new HashMap<>();
        result.put("title", title);
        result.put("aiSummary", aiSummary);
        return result;
    }

    // 支持前端传入政策ID，自动查库并AI解读（ID类型统一为String）
    public Map<String, Object> interpretPolicyById(String policyId) {
        PolicyInfo policy = policyInfoMapper.selectById(policyId);
        if (policy == null) {
            return Map.of("error", "未找到对应政策");
        }
        // 优先查数据库
        String dbSummary = policyInfoMapper.getAISummaryById(policyId);
        if (dbSummary != null && !dbSummary.isBlank()) {
            return Map.of("id", policyId, "title", getPolicyTitle(policy), "aiSummary", dbSummary, "from", "db");
        }
        String title = getPolicyTitle(policy);
        String content = getPolicyContent(policy);
        String prompt = "请用简明易懂的语言解读以下政策，突出对政策实施对象（企业或个人）的影响和建议，且不要出现#、*、-、•、·、●等符号，只输出纯净文本，可用一、二、三、等组织内容。：" + title + "。政策内容：" + content;
        String aiResult = callDeepSeek(prompt);
        // 优先用正则提取 JSON 代码块或大括号包裹的 JSON
        String summary = null;
        java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("```(?:json)?\\s*([\\s\\S]*?)\\s*```", java.util.regex.Pattern.CASE_INSENSITIVE);
        java.util.regex.Matcher matcher = pattern.matcher(aiResult);
        if (matcher.find()) {
            summary = matcher.group(1).trim();
        } else {
            int start = aiResult.indexOf('{');
            int end = aiResult.lastIndexOf('}');
            if (start >= 0 && end > start) {
                summary = aiResult.substring(start, end + 1);
            }
        }
        if (summary == null) {
            summary = aiResult;
        }
        // 清理AI摘要文本（每行去除开头符号）
        String cleanSummary = cleanAISummary(summary);
        // 确保AI内容记录存在，然后保存到数据库
        policyInfoMapper.insertAIContentIfNotExists(policyId);
        policyInfoMapper.updateAISummary(policyId, cleanSummary);
        return Map.of("id", policyId, "title", title, "aiSummary", cleanSummary);
    }
    // 工具方法：获取政策标题（可扩展为最细分字段）
    private String getPolicyTitle(PolicyInfo policy) {
        // 可根据实际字段补全
        if (policy == null) return "";
        // 兼容旧字段和新结构
        if (policy.getPolicyId() != null) return policy.getPolicyId();
        return "";
    }

    // 工具方法：获取政策正文内容（优先mainText字段）
    private String getPolicyContent(PolicyInfo policy) {
        if (policy == null) return "";
        if (policy.getMainText() != null && !policy.getMainText().isEmpty()) return policy.getMainText();
        return "";
    }
    /**
     * 去除AI产出内容每行开头的#、*、-、•、·、●等符号和多余空白，以及行内的**粗体标记
     */
    private String cleanAISummary(String text) {
        if (text == null) return "";
        
        // 首先清理行内的markdown格式符号
        text = text.replaceAll("\\*\\*([^*]+)\\*\\*", "$1"); // 移除**粗体**标记，保留内容
        text = text.replaceAll("\\*([^*]+)\\*", "$1"); // 移除*斜体*标记，保留内容
        text = text.replaceAll("~~([^~]+)~~", "$1"); // 移除~~删除线~~标记，保留内容
        text = text.replaceAll("`([^`]+)`", "$1"); // 移除`代码`标记，保留内容
        
        String[] lines = text.split("\\r?\\n");
        StringBuilder sb = new StringBuilder();
        for (String line : lines) {
            // 清理行首的符号
            String cleaned = line.replaceFirst("^[#*\\-•·●\\s]+", "");
            // 清理多余的空白字符
            cleaned = cleaned.replaceAll("\\s+", " ");
            if (!cleaned.trim().isEmpty()) {
                sb.append(cleaned.trim()).append("\n");
            }
        }
        return sb.toString().trim();
    }

    // 智能问答
    public Map<String, Object> aiQA(Map<String, Object> question) {
        String q = (String) question.getOrDefault("question", "");
        String prompt = "你是中国政策智能助手，请专业简明地回答用户问题：" + q;
        String answer = callDeepSeek(prompt);
        return Map.of("question", q, "answer", answer);
    }

    // 多政策对比分析
    @SuppressWarnings("unchecked")
    public Map<String, Object> comparePolicies(Map<String, Object> body) {
        List<?> policiesRaw = (List<?>) body.get("policies");
        List<Map<String, Object>> policies = null;
        if (policiesRaw != null) {
            policies = new ArrayList<>();
            for (Object o : policiesRaw) {
                if (o instanceof Map) {
                    policies.add((Map<String, Object>) o);
                }
            }
        }
        Object policyRaw = body.get("policy");
        Map<String, Object> policy = null;
        if (policyRaw instanceof Map) {
            policy = (Map<String, Object>) policyRaw;
        }
        String lang = (String) body.getOrDefault("lang", "zh");
        String prompt;
        if (policies != null && !policies.isEmpty()) {
            // 多条政策对比
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < policies.size(); i++) {
                Map<String, Object> p = policies.get(i);
                sb.append("政策").append(i + 1).append("：").append(p.getOrDefault("title", "")).append("\n");
                sb.append("摘要：").append(p.getOrDefault("summary", "")).append("\n");
                sb.append("部门：").append(p.getOrDefault("department", "")).append("\n");
                sb.append("日期：").append(p.getOrDefault("date", p.getOrDefault("publish_date", ""))).append("\n");
                Object tags = p.get("tags");
                if (tags instanceof List) {
                    List<String> tagList = new ArrayList<>();
                    for (Object t : (List<?>) tags) {
                        if (t instanceof String) tagList.add((String) t);
                    }
                    sb.append("标签：").append(String.join("，", tagList)).append("\n");
                }
                sb.append("\n");
            }
            prompt = ("zh".equals(lang) ?
                    "你是资深政策分析师，请用专业视角对以下多条政策进行结构化对比分析。请直接输出对比结论和要点，不要包含#、*、-、AI生成、总结、结论、分隔线等格式符号或提示性词语。请用简洁明了的Markdown表格展示主要对比项（如政策名称、部门、发布日期、核心内容、适用对象、亮点/不足），表格下方可补充简要分析。只输出内容本身，不要任何多余说明。"
                    : "You are a senior policy analyst. Please conduct a structured comparison analysis of the following policies from a professional perspective. Output only the comparison conclusions and key points, without any #, *, -, AI-generated, summary, conclusion, separator symbols or prompt words. Use a concise Markdown table to show the main comparison items (such as Policy Name, Department, Publish Date, Core Content, Target Audience, Highlights/Shortcomings), and add a brief analysis below the table. Output only the content itself, no extra explanation.")
                    + "\n" + sb;
        } else if (policy != null) {
            // 单条政策分析
            StringBuilder sb = new StringBuilder();
            sb.append("标题：").append(policy.getOrDefault("title", "")).append("\n");
            sb.append("摘要：").append(policy.getOrDefault("summary", "")).append("\n");
            sb.append("部门：").append(policy.getOrDefault("department", "")).append("\n");
            sb.append("日期：").append(policy.getOrDefault("date", policy.getOrDefault("publish_date", ""))).append("\n");
            Object tags = policy.get("tags");
            if (tags instanceof List) {
                List<String> tagList = new ArrayList<>();
                for (Object t : (List<?>) tags) {
                    if (t instanceof String) tagList.add((String) t);
                }
                sb.append("标签：").append(String.join("，", tagList)).append("\n");
            }
            sb.append("内容：").append(policy.getOrDefault("context", ""));
            prompt = ("zh".equals(lang) ?
                    "你是资深政策分析师，请用专业视角对单条政策进行简明概括和要点总结。请直接输出要点内容，不要包含#、*、-、AI生成、总结、结论、分隔线等格式符号，只输出纯净的分析文本。"
                    : "You are a senior policy analyst. Please summarize and extract key points for the following policy. Output only the key points, without any #, *, -, AI-generated, summary, conclusion, separator symbols or prompt words. Output only the pure analysis text.")
                    + "\n" + sb;
        } else {
            return Map.of("status", "error", "error", "未提供政策数据");
        }
        String result = callDeepSeek(prompt);
        return Map.of("status", "done", "result", result);
    }

    // 清理prompt中的控制字符，避免deepseek API报错
    private String sanitizePrompt(String prompt) {
        if (prompt == null) return "";
        // 替换所有不可见控制字符为一个空格
        return prompt.replaceAll("[\\u0000-\\u001F]", " ");
    }

    private String callDeepSeek(String prompt) {
        if (deepseekKey == null || deepseekKey.isEmpty()) {
            return "[AI服务未配置或Key缺失]";
        }
        try {
            HttpClient client = HttpClient.newHttpClient();
            String cleanPrompt = sanitizePrompt(prompt);
            String body = "{" +
                    "\"model\":\"deepseek-chat\"," +
                    "\"messages\":[{" +
                    "\"role\":\"user\",\"content\":\"" + cleanPrompt.replace("\"", "'") + "\"}]" +
                    "}";
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(DEEPSEEK_API))
                    .header("Content-Type", "application/json")
                    .header("Authorization", "Bearer " + deepseekKey)
                    .POST(HttpRequest.BodyPublishers.ofString(body))
                    .build();
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            String resp = response.body();
            // 用 Jackson 解析 content 字段
            try {
                com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
                Map<String, Object> respMap = mapper.readValue(resp, new com.fasterxml.jackson.core.type.TypeReference<Map<String, Object>>() {});
                Object choicesObj = respMap.get("choices");
                List<Map<String, Object>> choices = null;
                if (choicesObj != null) {
                    choices = mapper.convertValue(choicesObj, new com.fasterxml.jackson.core.type.TypeReference<List<Map<String, Object>>>() {});
                }
                if (choices != null && !choices.isEmpty()) {
                    Object msgObj = choices.get(0).get("message");
                    if (msgObj instanceof Map) {
                        @SuppressWarnings("unchecked")
                        Map<String, Object> message = (Map<String, Object>) msgObj;
                        if (message != null) {
                            return (String) message.get("content");
                        }
                    }
                }
            } catch (Exception e) {
                // fallback to old regex
            }
            // fallback: 用正则完整提取 "content":"...." 字段内容（支持多行和转义）
            java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("\"content\"\\s*:\\s*\"([\\s\\S]*?)\"");
            java.util.regex.Matcher matcher = pattern.matcher(resp);
            if (matcher.find()) {
                // 反转义
                return matcher.group(1).replace("\\n", "\n").replace("\\\"", "\"");
            }
            return resp;
        } catch (Exception e) {
            return "[AI服务调用失败]";
        }
    }

    // 分词（词云）
    public Map<String, Object> segmentText(Map<String, Object> body) {
        String text = (String) body.getOrDefault("text", "");
        if (text == null || text.trim().isEmpty()) {
            return Map.of("success", false, "error", "缺少文本内容");
        }
        // 使用jieba分词
        List<SegToken> tokens = jiebaSegmenter.process(text, JiebaSegmenter.SegMode.SEARCH);
        Map<String, Integer> freq = new HashMap<>();
        for (SegToken token : tokens) {
            String w = token.word;
            if (w.length() > 1) {
                freq.put(w, freq.getOrDefault(w, 0) + 1);
            }
        }
        List<Map<String, Object>> keywords = freq.entrySet().stream()
                .sorted((a, b) -> b.getValue() - a.getValue())
                .limit(30)
                .map(e -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("word", e.getKey());
                    map.put("count", e.getValue());
                    return map;
                })
                .collect(Collectors.toList());
        return Map.of("success", true, "keywords", keywords);
    }

    // AI脑图生成
    @SuppressWarnings("unchecked")
    public Map<String, Object> generateMindmap(Map<String, Object> body) {
        String text = (String) body.getOrDefault("text", "");
        String policyId = null;
        if (body.containsKey("policyId")) {
            policyId = String.valueOf(body.get("policyId"));
        }
        String dimension = (String) body.getOrDefault("dimension", "");
        int maxLevel = 3; // 最大层级调整为3，支持更完整的政策结构展示

        // 1. 仅查主题、时间、空间维度，无默认维度
        if (policyId != null) {
            String dbJson = null;
            if ("time".equalsIgnoreCase(dimension)) {
                dbJson = policyInfoMapper.getMindmapTimeJsonById(policyId);
            } else if ("space".equalsIgnoreCase(dimension)) {
                dbJson = policyInfoMapper.getMindmapSpaceJsonById(policyId);
            } else if ("theme".equalsIgnoreCase(dimension)) {
                dbJson = policyInfoMapper.getMindmapThemeJsonById(policyId);
            }
            if (dbJson != null && !dbJson.isBlank()) {
                try {
                    com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
                    Map<String, Object> mindmap = mapper.readValue(dbJson, Map.class);
                    fillChildren(mindmap);
                    simplifyMindmap(mindmap, 1, maxLevel);
                    return Map.of("success", true, "mindmap", mindmap, "from", "db");
                } catch (Exception e) {
                    return Map.of("success", false, "error", "数据库JSON解析失败", "exception", e.getMessage());
                }
            }
        }

        // 2. 如果有policyId但没有text，从数据库获取政策内容
        if ((text == null || text.trim().isEmpty()) && policyId != null) {
            PolicyInfo policy = policyInfoMapper.selectById(policyId);
            if (policy != null) {
                text = getPolicyContent(policy);
            }
        }

        // 3. 数据库无内容再调用AI
        if (text == null || text.trim().isEmpty()) {
            return Map.of("success", false, "error", "政策内容为空");
        }
        String prompt = "你是资深政策分析师，请将以下政策内容分解为清晰的3层结构，第一层为主要分类（最多5个），第二层为具体要点（每类下最多4个），第三层为细节说明（每个要点下最多3个），输出标准JSON对象，字段为title和children，children为数组。只输出JSON，不要任何说明。";
        if ("time".equalsIgnoreCase(dimension)) {
            prompt += " 请按时间维度（如发布时间、实施时间、有效期等）分层展示，突出时间节点和阶段性安排。";
        } else if ("space".equalsIgnoreCase(dimension)) {
            prompt += " 请按空间维度（如适用地区、管辖部门、实施范围等）分层展示，突出空间范围和层级关系。";
        } else if ("theme".equalsIgnoreCase(dimension)) {
            prompt += " 请按主题维度（如政策类型、核心内容、适用对象等）分层展示，突出核心主题和关键要素。";
        }
        prompt += "\n内容：" + text;
        String aiResult = callDeepSeek(prompt);

        // 只提取 markdown 代码块或大括号包裹的 JSON
        String json = null;
        java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("```(?:json)?\\s*([\\s\\S]*?)\\s*```", java.util.regex.Pattern.CASE_INSENSITIVE);
        java.util.regex.Matcher matcher = pattern.matcher(aiResult);
        if (matcher.find()) {
            json = matcher.group(1).trim();
        } else {
            int start = aiResult.indexOf('{');
            int end = aiResult.lastIndexOf('}');
            if (start >= 0 && end > start) {
                json = aiResult.substring(start, end + 1);
            }
        }
        if (json != null) {
            try {
                com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
                Map<String, Object> mindmap = mapper.readValue(json, Map.class);
                fillChildren(mindmap);
                simplifyMindmap(mindmap, 1, maxLevel);
                // 保存到数据库，按维度分别入库
                if (policyId != null && !dimension.isEmpty()) {
                    // 确保AI内容记录存在
                    policyInfoMapper.insertAIContentIfNotExists(policyId);
                    if ("time".equalsIgnoreCase(dimension)) {
                        policyInfoMapper.updateMindmapTimeJson(policyId, json);
                    } else if ("space".equalsIgnoreCase(dimension)) {
                        policyInfoMapper.updateMindmapSpaceJson(policyId, json);
                    } else if ("theme".equalsIgnoreCase(dimension)) {
                        policyInfoMapper.updateMindmapThemeJson(policyId, json);
                    }
                }
                return Map.of("success", true, "mindmap", mindmap, "raw", aiResult);
            } catch (Exception e) {
                return Map.of("success", false, "error", "AI JSON解析失败", "raw", aiResult, "exception", e.getMessage());
            }
        }
        return Map.of("success", false, "error", "AI结构化失败", "raw", aiResult);
    }

    // 递归补全children字段，保证每个节点有children数组
    private void fillChildren(Map<String, Object> node) {
        if (node == null) return;
        Object children = node.get("children");
        if (!(children instanceof List)) {
            node.put("children", new ArrayList<>());
        } else {
            List<?> list = (List<?>) children;
            for (Object child : list) {
                if (child instanceof Map<?, ?>) {
                    @SuppressWarnings("unchecked")
                    Map<String, Object> childMap = (Map<String, Object>) child;
                    fillChildren(childMap);
                }
            }
        }
    }

    // 结构图精简：限制最大层级，过滤冗余节点，合并同类项，限制每层节点数
    private void simplifyMindmap(Map<String, Object> node, int level, int maxLevel) {
        if (node == null) return;
        if (level > maxLevel) {
            node.put("children", new ArrayList<>()); // 超出层级直接清空
            return;
        }
        Object children = node.get("children");
        if (children instanceof List<?>) {
            List<Map<String, Object>> newChildren = new ArrayList<>();
            Set<String> titles = new HashSet<>();
            // 每层节点数量限制：第一层5个，第二层4个，第三层3个
            int maxChildrenPerLevel = level == 1 ? 5 : (level == 2 ? 4 : 3);
            
            for (Object child : (List<?>) children) {
                if (child instanceof Map<?, ?>) {
                    @SuppressWarnings("unchecked")
                    Map<String, Object> childMap = (Map<String, Object>) child;
                    String title = String.valueOf(childMap.getOrDefault("title", ""));
                    
                    // 增强过滤条件，根据层级调整标题长度要求
                    int minLength = level <= 2 ? 2 : 1; // 第三层允许更短的标题
                    int maxLength = level == 1 ? 25 : (level == 2 ? 20 : 15); // 按层级限制长度
                    
                    if (title.isBlank() || title.length() < minLength || title.length() > maxLength) continue;
                    
                    // 过滤常见无意义词汇（放宽第三层的过滤条件）
                    if (level <= 2) {
                        if (title.matches(".*[0-9]{4}.*") && title.length() > 10) continue; // 过滤包含年份的长标题
                        if (title.contains("条") && title.length() > 8) continue; // 过滤条款类长标题
                    }
                    
                    // 合并同名节点
                    if (titles.contains(title)) continue;
                    titles.add(title);
                    
                    // 限制每层节点数量
                    if (newChildren.size() >= maxChildrenPerLevel) break;
                    
                    simplifyMindmap(childMap, level + 1, maxLevel);
                    newChildren.add(childMap);
                }
            }
            node.put("children", newChildren);
        }
    }

    // AI流程图生成
    @SuppressWarnings("unchecked")
    public Map<String, Object> generateFlowchart(Map<String, Object> body) {
        String text = (String) body.getOrDefault("text", "");
        String policyId = null;
        if (body.containsKey("policyId")) {
            policyId = String.valueOf(body.get("policyId"));
        }
        // 优先查数据库已有内容
        if (policyId != null) {
            String dbFlowchart = policyInfoMapper.getFlowchartJsonById(policyId);
            if (dbFlowchart != null && !dbFlowchart.isBlank()) {
                try {
                    com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
                    Map<String, Object> flowchart = mapper.readValue(dbFlowchart, Map.class);
                    if (flowchart.containsKey("nodes") && flowchart.containsKey("links")) {
                        return Map.of("success", true, "flowchart", flowchart, "from", "db");
                    }
                } catch (Exception ignore) {}
            }
        }
        
        // 如果有policyId但没有text，从数据库获取政策内容
        if ((text == null || text.trim().isEmpty()) && policyId != null) {
            PolicyInfo policy = policyInfoMapper.selectById(policyId);
            if (policy != null) {
                text = getPolicyContent(policy);
            }
        }
        
        if (text == null || text.trim().isEmpty()) {
            return Map.of("success", false, "error", "缺少政策正文内容");
        }
        String prompt = "你是资深政策流程分析师，请将以下政策内容面向相关人员（如企业、个人、部门等）梳理出主要办理流程，输出标准JSON对象，包含nodes和links，nodes为流程节点（如{ id, name, type }），links为连接关系（如{ source, target, label }）。只输出JSON，不要任何说明。\n内容：" + text;
        String aiResult = callDeepSeek(prompt);
        System.out.println("[AI流程图原始返回]" + aiResult);

        // 提取JSON
        String json = null;
        java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("```(?:json)?\\s*([\\s\\S]*?)\\s*```", java.util.regex.Pattern.CASE_INSENSITIVE);
        java.util.regex.Matcher matcher = pattern.matcher(aiResult);
        if (matcher.find()) {
            json = matcher.group(1).trim();
        } else {
            int start = aiResult.indexOf('{');
            int end = aiResult.lastIndexOf('}');
            if (start >= 0 && end > start) {
                json = aiResult.substring(start, end + 1);
            }
        }
        if (json != null) {
            try {
                com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
                Map<String, Object> flowchart = mapper.readValue(json, Map.class);
                if (!flowchart.containsKey("nodes") || !flowchart.containsKey("links")) {
                    return Map.of("success", false, "error", "AI未生成完整流程结构", "raw", aiResult, "parsedJson", json);
                }
                // 新增：保存到数据库
                if (policyId != null) {
                    // 确保AI内容记录存在
                    policyInfoMapper.insertAIContentIfNotExists(policyId);
                    String flowchartJsonStr = mapper.writeValueAsString(flowchart);
                    policyInfoMapper.updateFlowchartJson(policyId, flowchartJsonStr);
                }
                return Map.of("success", true, "flowchart", flowchart, "raw", aiResult, "parsedJson", json);
            } catch (Exception e) {
                return Map.of("success", false, "error", "AI JSON解析失败", "raw", aiResult, "parsedJson", json, "exception", e.getMessage());
            }
        }
        return Map.of("success", false, "error", "AI结构化失败", "raw", aiResult);
    }

    /**
     * 生成政策对比图表数据
     */
    @SuppressWarnings("unchecked")
    public Map<String, Object> generateChartData(Map<String, Object> body) {
        List<?> policiesRaw = (List<?>) body.get("policies");
        String chartType = (String) body.getOrDefault("chartType", "impact");
        
        if (policiesRaw == null || policiesRaw.isEmpty()) {
            return Map.of("success", false, "error", "缺少政策数据");
        }
        
        List<Map<String, Object>> policies = new ArrayList<>();
        for (Object o : policiesRaw) {
            if (o instanceof Map) {
                policies.add((Map<String, Object>) o);
            }
        }
        
        if ("impact".equals(chartType)) {
            // 生成影响范围雷达图数据
            List<Map<String, Object>> indicator = Arrays.asList(
                Map.of("name", "经济影响", "max", 100),
                Map.of("name", "社会影响", "max", 100),
                Map.of("name", "环境影响", "max", 100),
                Map.of("name", "法律影响", "max", 100),
                Map.of("name", "技术影响", "max", 100),
                Map.of("name", "国际影响", "max", 100)
            );
            
            List<Map<String, Object>> series = new ArrayList<>();
            for (int i = 0; i < policies.size(); i++) {
                Map<String, Object> policy = policies.get(i);
                String title = (String) policy.getOrDefault("title", "政策" + (i + 1));
                
                // 根据政策类型生成模拟数据
                List<Integer> values = generateImpactValues(policy);
                
                series.add(Map.of(
                    "name", title,
                    "value", values
                ));
            }
            
            return Map.of(
                "success", true,
                "type", "radar",
                "data", Map.of(
                    "indicator", indicator,
                    "series", series
                )
            );
            
        } else if ("time".equals(chartType)) {
            // 生成时间线图数据
            List<String> categories = new ArrayList<>();
            Map<String, List<Integer>> seriesData = new HashMap<>();
            
            // 生成6个月的时间线
            String[] months = {"第1个月", "第2个月", "第3个月", "第4个月", "第5个月", "第6个月"};
            categories.addAll(Arrays.asList(months));
            
            for (int i = 0; i < policies.size(); i++) {
                Map<String, Object> policy = policies.get(i);
                String title = (String) policy.getOrDefault("title", "政策" + (i + 1));
                
                List<Integer> timelineValues = generateTimelineValues(policy);
                seriesData.put(title, timelineValues);
            }
            
            return Map.of(
                "success", true,
                "type", "line",
                "data", Map.of(
                    "categories", categories,
                    "series", seriesData
                )
            );
        }
        
        return Map.of("success", false, "error", "不支持的图表类型");
    }
    
    /**
     * 根据政策生成影响值
     */
    private List<Integer> generateImpactValues(Map<String, Object> policy) {
        String category = (String) policy.getOrDefault("category", "其他");
        
        Random random = new Random(policy.hashCode()); // 使用policy的hashCode作为种子，确保一致性
        
        List<Integer> values = new ArrayList<>();
        int baseValue = 60;
        
        // 根据政策类别调整基础值
        switch (category) {
            case "贸易政策":
                baseValue = 75;
                break;
            case "税收政策":
                baseValue = 70;
                break;
            case "投资政策":
                baseValue = 80;
                break;
            case "环保政策":
                baseValue = 65;
                break;
        }
        
        // 生成6个维度的值
        for (int i = 0; i < 6; i++) {
            int variance = random.nextInt(21) - 10; // -10到10的随机变化
            values.add(Math.max(20, Math.min(95, baseValue + variance)));
        }
        
        return values;
    }
    
    /**
     * 根据政策生成时间线值
     */
    private List<Integer> generateTimelineValues(Map<String, Object> policy) {
        Random random = new Random(policy.hashCode());
        
        List<Integer> values = new ArrayList<>();
        int startValue = 40 + random.nextInt(20); // 40-60之间的起始值
        
        // 生成6个月的递增趋势
        for (int i = 0; i < 6; i++) {
            int increment = 8 + random.nextInt(8); // 8-15的增长
            startValue = Math.min(95, startValue + increment);
            values.add(startValue);
        }
        
        return values;
    }
    
    /**
     * 导出分析结果
     */
    public Map<String, Object> exportAnalysis(Map<String, Object> body) {
        String format = (String) body.getOrDefault("format", "txt");
        String content = (String) body.getOrDefault("content", "");
        String title = (String) body.getOrDefault("title", "政策分析结果");
        
        if (content == null || content.trim().isEmpty()) {
            return Map.of("success", false, "error", "缺少导出内容");
        }
        
        try {
            // 清理HTML标记
            String cleanContent = content.replaceAll("<[^>]+>", "").trim();
            
            // 生成文件名
            String timestamp = new java.text.SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            String filename = title + "_" + timestamp + "." + format;
            
            // 根据格式处理内容
            if ("pdf".equals(format)) {
                // 对于PDF，返回处理后的内容和元数据，实际PDF生成在前端完成
                return Map.of(
                    "success", true,
                    "format", "pdf",
                    "filename", filename,
                    "content", cleanContent,
                    "metadata", Map.of(
                        "title", title,
                        "timestamp", timestamp,
                        "size", cleanContent.length()
                    )
                );
            } else {
                // TXT格式
                return Map.of(
                    "success", true,
                    "format", "txt",
                    "filename", filename,
                    "content", cleanContent,
                    "size", cleanContent.length()
                );
            }
            
        } catch (Exception e) {
            return Map.of("success", false, "error", "导出失败: " + e.getMessage());
        }
    }

}
